<?php
	include_once("global_modules.php");
	
	/**
	 * This function returns the data of active resources reservation, in one user.
	 * @param $user_id Integer containing the user id.
	 * @return Array containing the user reservations (id, slice_id, resource_list, begin_time, end_time, full_flag).
	 */
	function get_my_reservations($user_id){
		$connection = database_connect();
		
		$query = database_query($connection, "SELECT * FROM reservation WHERE user_id = ".$user_id."");
		
		$reservation_list = array();
		$row = 0;
		while($results = database_fetch_object($query, $row)){
			$reservation_list[] = array(
								'id' => $results->id,
								'slice_id' => $results->slice_id,
								'resource_list' => get_reservation_resources($results->id, $connection),
								'begin_time' => $results->begin_time,
								'end_time' => $results->end_time,
								'full_flag' => $results->full
							);
			
			$row++;
		}
		
		database_close($connection);
		
		return $reservation_list;
	}
    
    /**
     * This function return the reserved resource(s) list in the future
     * @param $type String containing the type of resource to be searched.
     * @return Array containing the slice, resource and reservation data.
     */
    function get_reserved_resources($type="ALL"){
		$connection = database_connect();
		
		$resource_types = array('node', 'channel');
        
        $now = date("Y-m-d H:i:s", time());
        $query_string = "SELECT slice_id, reservation_id, begin_time, end_time, resource_id, " .
                        "user_id FROM reservation, resource_reservation WHERE " .
                        "(reservation.id = resource_reservation.reservation_id) AND " .
                        "end_time >= '". $now ."'";
        
		$query = database_query($connection, $query_string);
		
		$reserved_resources_list = array();
		$row = 0;
		while($results = database_fetch_object($query, $row)){
			$resource_query = database_query($connection, "SELECT * FROM resources WHERE id = ".$results->resource_id."");
            $resource = database_fetch_object($resource_query);
            
            if( ($type != "ALL" && in_array($type, $resource_types)) && $resource->type != $type ){
                $row++;
                continue;
            }

            $real_resource_query = database_query($connection, "SELECT * FROM ".$resource->type." WHERE id = ".$resource->real_resource_id."");
			$resource_details = database_fetch_array($real_resource_query);
			
			$resource = array(
                            'id' => $results->resource_id,
                            'type' => $resource->type,
                            'status' => $resource->status,
                            'resource_details' => $resource_details
                        );
            
            
            $slice_query = database_query($connection, "SELECT * FROM slice WHERE id = ".$results->slice_id."");
            $slice = database_fetch_array($slice_query);
            
			$reserved_resources_list[] = array(
								'reservation_id' => $results->reservation_id,
								'begin_time' => $results->begin_time,
								'end_time' => $results->end_time,
                                'user_id' => $results->user_id,
								'resource' => $resource,
                                'slice' => $slice
							);
			
			$row++;
		}
		
		database_close($connection);
		
		return $reserved_resources_list;
    }
	
	/**
	 * This function return the resource(s) id(s) of a reservation.
	 * @param $reservation_id Integer containing the reservation id.
	 * @param $connection DatabaseConnection containing the open connection to database.
	 * @return Array containing the id list of resources of a reservation.
	 */
	function get_reservation_resources($reservation_id, $connection=NULL){
		$new_connection = ($connection == NULL) ? database_connect() : $connection;
		
		$query = database_query($new_connection, "SELECT resource_id FROM resource_reservation WHERE reservation_id = ".$reservation_id."");
		
		$resource_list = array();
		$row = 0;
		while($results = database_fetch_object($query, $row)){
			$resource_list[] = $results->resource_id;
			$row++;
		}
		
		if($connection == NULL)
			database_close($new_connection);
		
		return $resource_list;
	}
	
	/**
	 * This function returns the id of available resources in a given moment (comprising the interval between begin and end time).
	 * @param $begin_time Date containing the begin time.
	 * @param $end_time Date containing the end time.
	 * @param $type String containing the type of resources to be searched (if you want all types, use the default string 'ALL').
	 * @return Array contaning the id of available resources.
	 */
	function get_free_resources($begin_time, $end_time, $type="ALL"){
		$connection = database_connect();
		
		$resource_types = array('node', 'channel');
		$filter_by_type = "";
		
		$time_in_query = "((('".$begin_time."' >= begin_time) AND ('".$end_time."' <= end_time))".
						 " OR (('".$begin_time."' >= begin_time) AND ('".$begin_time."' < end_time))".
						 " OR (('".$end_time."' >= begin_time) AND ('".$end_time."' <= end_time))".
						 " OR (('".$begin_time."' <= begin_time) AND ('".$end_time."' >= end_time)))";
		
		$query = database_query($connection, "SELECT * FROM reservation WHERE ".$time_in_query."");
		
		$reserved_resource_list = array();
		$row = 0;
		while($results = database_fetch_object($query, $row)){
			$resource_id_query = database_query($connection, "SELECT resource_id FROM resource_reservation WHERE reservation_id = ".$results->id."");
			
			$row2 = 0;
			while($reserved_resource_results = database_fetch_object($resource_id_query, $row2)){
				$reserved_resource_list[] = $reserved_resource_results->resource_id;
				$row2++;
			}

			$row++;
		}
		
		if($type != "ALL" && in_array($type, $resource_types))
			$filter_by_type = "AND type = '".$type."'";
		
		$query_resources = database_query($connection, "SELECT * FROM resources WHERE status = 0 ".$filter_by_type."");
		
		$resource_list = array();
		$row = 0;
		while($resource_results = database_fetch_object($query_resources, $row)){
			$resource_list[] = $resource_results->id;
			$row++;
		}
		
		database_close($connection);
		
		$free_resource_list = array();
		for($i = 0; $i < count($resource_list); $i++){
			if(!in_array($resource_list[$i], $reserved_resource_list))
				$free_resource_list[] = $resource_list[$i];
		}
		
		return $free_resource_list;
	}

	/**
	 * This function returns true if the resource is not reserved by a user between a given begin time (start) and end time (end).
	 * @param $resource_id Integer containing the resource id.
	 * @param $begin_time Date containing the begin time.
	 * @param $end_time Date containing the end time.
	 * @return Boolean TRUE if resource is available or FALSE otherwise.
	 */
	function is_resource_available($resource_id, $begin_time, $end_time){
		$connection = database_connect();
		
		$time_in_query = "((('".$begin_time."' >= begin_time) AND ('".$end_time."' <= end_time))".
						 " OR (('".$begin_time."' >= begin_time) AND ('".$begin_time."' < end_time))".
						 " OR (('".$end_time."' >= begin_time) AND ('".$end_time."' <= end_time))".
						 " OR (('".$begin_time."' <= begin_time) AND ('".$end_time."' >= end_time)))";
						 
		$query = database_query($connection, "SELECT * FROM reservation WHERE ".$time_in_query."");
		
		$row = 0;
		while($results = database_fetch_object($query, $row)){
			$resource_id_query = database_query($connection, "SELECT resource_id FROM resource_reservation WHERE reservation_id = ".$results->id."");
			
			$row2 = 0;
			while($resource_results = database_fetch_object($resource_id_query, $row2)){
				if($resource_results->resource_id == $resource_id)
					return FALSE;
				
				$row2++;
			}
			$row++;
		}
		
		return TRUE;
	}
	
	/**
	 * Create a slice reservation.
	 * @param $user_id Integer containing the user id.
	 * @param $slice_id Integer containing the slice_id.
	 * @param $begin_time Date containing the begin time.
	 * @param $end_time Date containing the end time.
	 * @return Integer containing the reservation id.
	 */
	function create_reservation($user_id, $slice_id, $begin_time, $end_time){
		require_once("resources.php");
		
		// Creating a reservation:
		$connection = database_connect();
			
		$query = "INSERT INTO reservation (slice_id, begin_time, end_time, user_id) VALUES (".$slice_id.", '".$begin_time."', '".$end_time."', ".$user_id.")";
		$reservation_insert = database_query($connection, $query);
		
		$query_reservation_id = database_query($connection, "SELECT id FROM reservation ORDER BY id DESC LIMIT 1");
		$reservation_id = database_fetch_object($query_reservation_id);
		$reservation_id = $reservation_id->id;
		
		database_close($connection);
		
		// Trying to reserve include the selected resources in the resevation:
		$reservation_resources = get_slice_resources($slice_id);
		$reserved_resources = 0;
		for($i = 0; $i < count($reservation_resources); $i++){
			if(is_resource_available($reservation_resources[$i], $begin_time, $end_time)){
				add_resource_to_reservation($reservation_resources[$i], $reservation_id);
				$reserved_resources++;
			}
		}
		
		// If we reserved 100% of slice resources, set the flag full to TRUE
		if(count($reservation_resources) == $reserved_resources){
			$connection = database_connect();
			
			$query = "UPDATE reservation SET \"full\" = TRUE WHERE id = ".$reservation_id."";
			$update_reservation = database_query($connection, $query);
			
			database_close($connection);
		}
		
		return $reservation_id;
	}
	
	/**
	 * This function add a resource to reservation.
	 * @param $resource_id Integer containing the resource id.
	 * @param $reservation_id Integer containing the reservation id.
	 * @return boolean TRUE when the resource was successfully added to the reservation or FALSE when not. 
	 */
	function add_resource_to_reservation($resource_id, $reservation_id){
		$connection = database_connect();
		
		$query = "INSERT INTO resource_reservation (resource_id, reservation_id) VALUES (".$resource_id.", ".$reservation_id.")";
		$rr_insert = database_query($connection, $query);
		
		database_close($connection);
		
		if($rr_insert)
			return TRUE;
		else
			return FALSE;
	}
	
	/**
	 * This function remove a resource from reservation.
	 * @param $resource_id Integer containing the resource id.
	 * @param $reservation_id Integer containing the reservation id.
	 * @return boolean TRUE when the resource was successfully removed from the reservation or FALSE when not. 
	 */
	function delete_resource_from_reservation($resource_id, $reservation_id){
		$connection = database_connect();
		
		$query = "DELETE FROM resource_reservation WHERE resource_id = ".$resource_id." AND reservation_id = ".$reservation_id."";
		$rr_remove = database_query($connection, $query);
		
		$query = "UPDATE reservation SET \"full\" = FALSE WHERE id = ".$reservation_id."";
		$update_reservation = database_query($connection, $query);
		
		database_close($connection);
		
		if($rr_remove)
			return TRUE;
		else
			return FALSE;
	}
	
	/**
	 * This function cancels a slice reservation.
	 * @param $reservation_id Integer containing the reservation id.
	 * @return boolean TRUE when the reservation was successfully canceled or FALSE when not.
	 */
	function cancel_reservation($reservation_id){
		$connection = database_connect();
		
		$query = "DELETE FROM reservation WHERE id = ".$reservation_id."";
		$reservation_cancel = database_query($connection, $query);
		
		database_close($connection);
		
		if($reservation_cancel)
			return TRUE;
		else
			return FALSE;
	}
?>
